﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.ServiceModel;
//using System.Globalization;
//using YTV.Utilities;


namespace YTV
{
    namespace MUpL
    {
        public partial class CompReadUpdateConfigFile : Component
        {
            static bool IsSourceSet = false;
            static public ReadUpdateApplConfigFile staticReadUpdateApplConfigFile = GetReadUpdateApplConfigFile(false);
            static public BindingSource bs;
            public CompReadUpdateConfigFile()
            {
                InitializeComponent();
                //DataSetView.DataSource = staticReadUpdateApplConfigFile.ds.Tables[0];
                
            }

            public CompReadUpdateConfigFile(IContainer container)
            {
                container.Add(this);

                InitializeComponent();
                //DataSetView.DataSource = staticReadUpdateApplConfigFile.ds.Tables[0];
                
            }
            public bool SetSource(bool value)
            {
                    IsSourceSet = value;
                    
                    if (IsSourceSet == true)
                    {
                        if (!staticReadUpdateApplConfigFile.IsLoadedConfigFile)
                        {
                        staticReadUpdateApplConfigFile.IsLoadedConfigFile = true;
                        staticReadUpdateApplConfigFile.LoadConfigFile();
                        }
                        if (staticReadUpdateApplConfigFile.ds.Tables.Count > 0)
                        {
                            bs = new BindingSource();
                            bs.DataSource = staticReadUpdateApplConfigFile.ds.Tables["add"];
                        }
                        
                        return true;
                    }
                    else
                    {
                        if (bs != null)
                        {
                            bs.DataSource = null;
                        }
                        bs = null;
                        return false;
                    }
                    
                
            }
            public bool ShowConfigEditDialog()
            {
                if (!staticReadUpdateApplConfigFile.IsLoadedConfigFile)
                {
                    staticReadUpdateApplConfigFile.IsLoadedConfigFile = true;
                    staticReadUpdateApplConfigFile.LoadConfigFile();
                }
                return staticReadUpdateApplConfigFile.CreateXMLEditDialog();
            }
            static private ReadUpdateApplConfigFile GetReadUpdateApplConfigFile(bool ReadConfogFile = true)
            {
                return new ReadUpdateApplConfigFile(ReadConfogFile);
            }
            static public XMuL GetReadUpdateXMuLanFile()
            {
                return new XMuL();
            }
            public class ReadUpdateApplConfigFile : XMuL
            {
                public readonly string MachineConfig = System.Runtime.InteropServices.RuntimeEnvironment.SystemConfigurationFile;
                const string Vhost = ".vshost";
                string[] listConfFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.config");
                //ConfigXmlDocument CZMLDoc = new ConfigXmlDocument();
                public ReadUpdateApplConfigFile(bool bLoadConfigFile)
                {
                    //InitializeComponent();
                    FilterFileExt.Add(".config");
                    IsLoadedConfigFile = bLoadConfigFile;
                    if (IsLoadedConfigFile)
                    {
                        excCl = LoadConfigFile();
                        if (excCl != null)
                            throw excCl;
                    }
                    GetListFilesCurDir();
                    
                }

                private ReadUpdateApplConfigFile()
                    : this(true)
                {
                    FilterFileExt.Add(".config");
                    GetListFilesCurDir();
                }
               
                public MUplException LoadConfigFile()
                {
                    int len;
                    MUplInpFilePath = "";
                    string iMUplInpFilePath = Process.GetCurrentProcess().ProcessName;
                    //iMUplInpFilePath.
                    if (iMUplInpFilePath.EndsWith(Vhost))
                    {
                        len = iMUplInpFilePath.Length - Vhost.Length;
                        iMUplInpFilePath = iMUplInpFilePath.Substring(0, len) + ".exe.config";
                    }
                    else
                    {
                        iMUplInpFilePath = iMUplInpFilePath + ".exe.config";
                    }
                    len = iMUplInpFilePath.Length;
                    string ss;
                    foreach (string s in listConfFiles)
                    {
                        if (len >= s.Length)
                            continue;
                        ss = s.Substring(s.Length - len, len);
                        if (iMUplInpFilePath == ss)
                        {
                            if (!File.Exists(s))
                            {
                                continue;
                            }
                            MUplInpFilePath = s;
                            break;
                        }
                    }
                    if (MUplInpFilePath == "")
                    {
                        return new MUplException("Can not Find Configuration File-" + listConfFiles.ToString(), null);
                    }
                    if (ds != null)
                        ds.Clear();
                    if (LoadXML())
                    {
                        DataTable t = ds.Tables["add"];
                        DataColumn c = t.Columns["key"];
                        DataColumn[] cs = new DataColumn[] { c };
                        t.PrimaryKey = cs;
                    }
                    else
                    {
                        return new MUplException("Can not Load Configuration File-" + MUplInpFilePath, null);
                    }
                    return null;
                }
                public string Find(string PrimKey)
                {
                    DataRow dr = null;
                    try
                    {
                        dr = ds.Tables["add"].Rows.Find(PrimKey);
                    }
                    catch (Exception)
                    {

                    }
                    return dr != null ? dr["value"].ToString() : null;
                }
                public bool Update(string PrimKey, string NewValue)
                {
                    DataRow dr = ds.Tables["add"].Rows.Find(PrimKey);
                    dr["value"] = NewValue;
                    IsSaveChanges = true;
                    return true;
                }
                ~ReadUpdateApplConfigFile()
                {
                    if (bs != null)
                    {
                        bs.DataSource = null;
                    }
                    bs = null;
                }
            }
            public class XMuL : MUpL
            {
                public DataSet ds;
                EditXmlConfigDialog dlg;
                public bool CreateXMLEditDialog()
                {
                    try
                    {
                        dlg = new EditXmlConfigDialog(ds, bs);
                        dlg.Show();
                    }
                    catch (Exception e)
                    {
                        excCl = new MUplException(e.Message, e);
                        NotifyError(excCl);
                        return false;
                    }
                    return true;
                }
                public XMuL()
                {
                    FilterFileExt.Add(".xml");
                }
                public bool LoadXML()
                {
                    try
                    {
                        if (ds == null)
                            ds = new DataSet(MUplInpFilePath);
                        else
                            ds.Clear();
                        ds.ReadXml(MUplInpFilePath);
                    }
                    catch (Exception e)
                    {
                        excCl = new MUplException("Can not Load XML file " + MUplInpFilePath, e);
                        NotifyError(excCl);
                        return false;
                    }
                    return true;
                }
                public string Find(string PrimKey, string ColName, string Table)
                {
                    DataRow dr = ds.Tables[Table].Rows.Find(PrimKey);
                    return dr != null ? dr[ColName].ToString() : null;
                }
                public bool SaveChanges()
                {
                    if (IsSaveChanges && ds != null && MUplInpFilePath != "")
                    {
                        try
                        {
                            if (IsWriteSchema)
                            {
                                ds.WriteXml(MUplInpFilePath, XmlWriteMode.WriteSchema);
                            }
                            else
                            {
                                ds.WriteXml(MUplInpFilePath, XmlWriteMode.IgnoreSchema);
                            }
                            IsSaveChanges = false;
                            return true;
                        }
                        catch (Exception e)
                        {
                            NotifyError(new MUplException("Can not Update XML file " + MUplInpFilePath, e));
                        }

                    }
                    return false;
                }
                ~XMuL()
                {
                    SaveChanges();
                }
            }
            public class MUpL
            {
                public bool IsLoadedConfigFile = false;
                public MUplException excCl;
                public event EventHandler NotifyErrorEvent;
                public string MUplInpFilePath = "";
                public bool IsSaveChanges = false;
                public bool IsWriteSchema = false;
                public List<string> ListFiles=new List<string>();
                public List<string> FilterFileExt = new List<string>();
                protected MUpL()
                {

                }
                public int GetListFilesCurDir()
                {
                    string cd = Directory.GetCurrentDirectory();
                    string[] lf = Directory.GetFiles(cd);
                    ListFiles.Clear();
                    foreach(string f in lf)
                    {
                        if (FilterFileExt.Count > 0)
                        {
                            foreach (string ext in FilterFileExt)
                            {                                
                                if (f.EndsWith(ext,true,null))
                                {
                                    ListFiles.Add(f);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            ListFiles.Add(f);
                        }
                    }
                    return ListFiles.Count;
                }
                public bool NotifyError(MUplException e)
                {
                    try
                    {
                        NotifyErrorEvent.Invoke(this, new MUpLEventArg(e));
                        return true;
                    }
                    catch (Exception)
                    {
                        return false;
                    }

                }

            }

            private void bindingSource1_CurrentChanged(object sender, EventArgs e)
            {

            }
        }
    }
}
